package com.hb.unic.websupport.filter;

import java.io.IOException;
import java.util.Arrays;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import com.hb.unic.core.base.constant.ISpecialSymbol;
import com.hb.unic.core.context.Application;
import com.hb.unic.core.log.UnicLogger;
import com.hb.unic.core.log.UnicLoggerFactory;
import com.hb.unic.core.util.IpUtils;

/**
 * 拦截黑名单请求
 *
 * @author Mr.huang
 * @since 2020/4/21 9:07
 */
public class BlackListAccessFilter extends OncePerRequestFilter {

    /**
     * log
     */
    private static final UnicLogger LOGGER = UnicLoggerFactory.getLogger(BlackListAccessFilter.class);

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
        throws ServletException, IOException {
        String ipAddr = IpUtils.getIpAddr(request);
        String blackListIps = Application.getProperties().get("request.blacklist.ips");
        if (!StringUtils.isEmpty(blackListIps)) {
            String[] blackListIpArr = blackListIps.split(ISpecialSymbol.COMMA);
            boolean anyMatch = Arrays.asList(blackListIpArr).contains(ipAddr);
            if (anyMatch) {
                LOGGER.info("Access forbidden, url:{}", ipAddr);
                return;
            }
        }
        chain.doFilter(request, response);
    }

}
